package com.ce.framework.pool;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.logicalcobwebs.proxool.ProxoolDataSource;

/**
 * 功能：数据源解密工具类
 * 
 * @author ShouCai.Wang
 * @since 2011-10-24 上午10:29:43
 */
public class DataBaseConnectionPool extends ProxoolDataSource {

    private String user, pwd;

    public String getUser() {

	// 用户名解密
	if (user == null) {
	    user = decrypt(super.getUser());
	}
	return user;

    }

    public String getPassword() {

	// 密码解密
	if (pwd == null) {
	    pwd = decrypt(super.getPassword());
	}
	return pwd;
    }

    public static void main(String[] arg) {
	DataBaseConnectionPool dp = new DataBaseConnectionPool();
	System.out.println(decrypt("213D6K4F1P2P652u49444a4t333U3c0F"));
    }

    private static String PASSWORD_CRYPT_KEY = "hh_csmis";

    public static String decrypt(String str) {
	return decrypt(str, PASSWORD_CRYPT_KEY);
    }

    public static String decrypt(String str, String key) {
	try {
	    byte[] src = ByteUtil.fromStrings(str);
	    SecureRandom sr = new SecureRandom();
	    DESKeySpec dks = new DESKeySpec(key.getBytes());
	    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
	    SecretKey securekey = keyFactory.generateSecret(dks);
	    Cipher cipher = Cipher.getInstance("DES");
	    cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
	    byte[] bytes = cipher.doFinal(src);
	    return new String(bytes);
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return "";
    }

}

class ByteUtil {
    private static int RADIO = 36;

    public static String toStr(byte b) {
	String tmp = Integer.toString(128 + b, RADIO);
	tmp = tmp.length() < 2 ? "0" + tmp : tmp;
	if (Math.random() > 0.5) {
	    tmp = tmp.toUpperCase();
	}
	return tmp;
    }

    public static String toStr(byte[] buff) {
	StringBuffer sb = new StringBuffer();
	for (byte b : buff) {
	    sb.append(toStr(b));
	}
	return sb.toString();
    }

    public static byte fromStr(String str) {
	int i = Integer.parseInt(str, RADIO) - 128;
	return (byte) i;
    }

    public static byte[] fromStrings(String str) {
	byte[] buff = new byte[str.length() / 2];
	for (int i = 0; i <= str.length() - 2; i += 2) {
	    buff[i / 2] = fromStr(str.substring(i, i + 2));
	}
	return buff;
    }

}
